package cn.easier.activity.console.repository;

import cn.easier.activity.console.entity.ActivityConsoleUser;
import cn.easier.activity.console.entity.ActivityMessages;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 后台用户 Repository
 */
@Repository
public interface ActivityConsoleUserRepository extends JpaRepository<ActivityConsoleUser, Integer> {

    /**
     * 根据用户名获取用户
     *
     * @param username 活动编号
     * @return
     */
    ActivityConsoleUser findActivityConsoleUserByUsernameAndEnabled(String username, boolean enabled);

    @Query(value = "select a.uid,a.username,a.phone_num,a.authorities_str,a.enabled,a.nick_name,a.register_date,b.activity,b.email,b.look_data,b.message,b.email_and_sms " +
            "from activity_console_user as a " +
            "LEFT JOIN activity_role_user as b on a.`username` = b.`username` where ((:userName is null or :userName = '') or a.`username` = :userName) " +
            "order by a.uid desc LIMIT :pageCount , :pageSize ", nativeQuery = true)
    List<Object[]> findAllBy(@Param("userName") String userName, @Param("pageCount") int pageCount, @Param("pageSize") int pageSize);

    @Query(value = "select count(a.uid) from activity_console_user a where ((:userName is null or :userName = '') or a.`username` = :userName) order by a.uid desc ", nativeQuery = true)
    long findAllByCount(@Param("userName") String userName);


    @Query(value = "UPDATE `activity_console_user` SET enabled = ?2 WHERE uid = ?1", nativeQuery = true)
    @Modifying
    int changeEnabled(Integer id, boolean enabled);

    @Query(value = "UPDATE `activity_console_user` SET authorities_str = ?2 WHERE uid = ?1", nativeQuery = true)
    @Modifying
    int changeAuthoritiesStr(Integer id, String authoritiesStr);

    List<ActivityConsoleUser> findByUsername(String username);

    ActivityConsoleUser findByUid(Long uid);

    List<ActivityConsoleUser> findByNickNameAndUidIsNot(String nickName, Long uid);

    List<ActivityConsoleUser> findByPhoneNumAndUidIsNot(Long phoneNum, Long uid);

    List<ActivityConsoleUser> findByPhoneNum(Long phoneNum);


}
